package com.house.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.common.context.BaseContext;
import com.house.common.context.Dictionaries;
import com.house.common.context.RedisContext;
import com.house.model.dto.MessageDto;
import com.house.model.dto.MessageListVo;
import com.house.model.entity.InformationRecord;
import com.house.model.entity.User;
import com.house.model.vo.MessageContactVO;
import com.house.model.vo.MessageVO;
import com.house.service.mapper.InformationRecordMapper;
import com.house.service.mapper.UserMapper;
import com.house.service.service.IInformationRecordMapperService;
import com.house.util.MySortList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class InformationRecordMapperServiceImpl extends ServiceImpl<InformationRecordMapper, InformationRecord> implements IInformationRecordMapperService {

    @Autowired
    private InformationRecordMapper informationRecordMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<MessageContactVO> findContact() {
        String userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<InformationRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(InformationRecord::getSendUserId, userId).or().eq(InformationRecord::getGatherUserId, userId);
        lambdaQueryWrapper.orderByAsc(InformationRecord::getCreateDate);
        List<InformationRecord> informationRecords = informationRecordMapper.selectList(lambdaQueryWrapper);
        HashMap<String, MessageContactVO> contacts = new HashMap<>();
        // 获取所有我发过信息和给我发过信息的联系人信息
        for (InformationRecord informationRecord : informationRecords) {
            // 给我发过信息的联系人
            if (!informationRecord.getSendUserId().equals(userId)){
                if(!contacts.containsKey(informationRecord.getSendUserId())){
                    MessageContactVO messageContactVO = new MessageContactVO();
                    messageContactVO.setUserId(informationRecord.getSendUserId());
                    messageContactVO.setCreateDate(informationRecord.getCreateDate());
                    messageContactVO.setContent(informationRecord.getContent());
                    if (informationRecord.getIsRead() == 0){
                        messageContactVO.setIsReadCount(1);
                    }
                    contacts.put(informationRecord.getSendUserId(),messageContactVO);
                }else {
                    MessageContactVO messageContactVO = contacts.get(informationRecord.getSendUserId());
                    messageContactVO.setCreateDate(informationRecord.getCreateDate());
                    messageContactVO.setContent(informationRecord.getContent());
                    if (informationRecord.getIsRead() == 0){
                        messageContactVO.setIsReadCount(messageContactVO.getIsReadCount()+1);
                    }
                }
            }
            if (!informationRecord.getGatherUserId().equals(userId)){
                if (!contacts.containsKey(informationRecord.getGatherUserId())){
                    MessageContactVO messageContactVO = new MessageContactVO();
                    messageContactVO.setUserId(informationRecord.getGatherUserId());
                    messageContactVO.setCreateDate(informationRecord.getCreateDate());
                    messageContactVO.setContent(informationRecord.getContent());
                    contacts.put(informationRecord.getGatherUserId(),messageContactVO);
                } else {
                    MessageContactVO messageContactVO = contacts.get(informationRecord.getGatherUserId());
                    messageContactVO.setCreateDate(informationRecord.getCreateDate());
                    messageContactVO.setContent(informationRecord.getContent());
                }
            }
        }
        ArrayList<MessageContactVO> messageContactVOS = new ArrayList<>();
        contacts.forEach((key,value) -> {
            User user = userMapper.selectById(key);
            value.setName(user.getName());
            value.setProfilePhoto(user.getProfilePhoto());
            messageContactVOS.add(value);
        });
        return messageContactVOS;
    }

    @Override
    public List<MessageListVo> getMessageList(String userId) {

        String sendUserId = BaseContext.getCurrentId();
        // 将所有信息修改为已读
        informationRecordMapper.updateStates(userId,sendUserId);
        // 查询所有消息
        List<MessageVO> messageVOS = informationRecordMapper.selectListByUserId(sendUserId, userId);
        List<MessageVO> collect = messageVOS.stream()
                .filter(messageVO -> messageVO.getSendUserId().equals(sendUserId) || messageVO.getSendUserId().equals(userId))
                .filter(messageVO -> messageVO.getGatherUserId().equals(sendUserId) || messageVO.getGatherUserId().equals(userId))
                .collect(Collectors.toList());
        List<MessageListVo> lists = new ArrayList<>();
        for (MessageVO messageVO : collect) {
            MessageListVo messageListVo = new MessageListVo();
            if (messageVO.getSendUserId().equals(sendUserId)){
                messageListVo.setUserContent(messageVO.getContent());
                messageListVo.setImage(messageVO.getSendUserImage());
                messageListVo.setBotContent("");
            }else{
                messageListVo.setBotContent(messageVO.getContent());
                messageListVo.setImage(messageVO.getSendUserImage());
                messageListVo.setUserContent("");
            }
            lists.add(messageListVo);
        }
        return lists;
    }

    @Override
    public MessageListVo sendMessage(MessageDto messageDto) {
        String sendUserId = BaseContext.getCurrentId();

        // 存入redis
        redisTemplate.opsForValue().set(RedisContext.MESSAGE+sendUserId+":"+messageDto.getGatherUserId(),1);

        InformationRecord informationRecord = new InformationRecord();
        BeanUtils.copyProperties(messageDto,informationRecord);
        informationRecord.setSendUserId(sendUserId);
        informationRecord.setIsRead(Dictionaries.MESSAGE_IS_READ);
        informationRecord.setCreateDate(new Date());
        int insert = informationRecordMapper.insert(informationRecord);
        User user = userMapper.selectById(sendUserId);
        MessageListVo messageListVo = new MessageListVo();
        messageListVo.setUserContent(informationRecord.getContent());
        messageListVo.setBotContent("");
        messageListVo.setImage(user.getProfilePhoto());
        return messageListVo;
    }

}
